"use client";
import { memo, useState, useEffect, useCallback } from "react";
import type { ReactNode, FC } from "react";
import styles from "./style.module.scss";
interface IProps {
  children?: ReactNode;
}

const BackToTop: FC<IProps> = (props) => {
  const [isVisible, setIsVisible] = useState(false);

  const toggleVisibility = useCallback(() => {
    if (window.pageYOffset > 300) {
      setIsVisible(true);
    } else {
      setIsVisible(false);
    }
  }, [window.pageYOffset]);

  const scrollToTop = useCallback(() => {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  }, []);

  useEffect(() => {
    window.addEventListener("scroll", toggleVisibility);
    return () => {
      window.removeEventListener("scroll", toggleVisibility);
    };
  }, []);

  return (
    <a className={styles.backToTopWrapper}>
      {isVisible && (
        <button
          className={`${styles.btns} sprite`}
          onClick={scrollToTop}
        ></button>
      )}
    </a>
  );
};

export default memo(BackToTop);
